package views

import (
	"strings"
	"strconv"
	"net/http"
	"appengine"
	"appengine/blobstore"
	"appengine/datastore"
	"mdbook/model/file"
	"mdbook/gorilla/mux"
)


// 文件处理
func UploadHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	f, err := file.SaveFile(r, "file")
	if err != nil {
		c.Errorf("SAVE FILE ERROR: %v", err)
		renderJSON(w, r, &file.File{})
		return
	}

	q := datastore.NewQuery("File").Order("-Id").Limit(1)
	var ff []*file.File
	var max int64
	_, err = q.GetAll(c, &ff)
	if err != nil {
		c.Infof("GET FILE MAXID ERROR: %v", err)
		max = 1
	}
	if len(ff) == 0 {
		max = 1
	} else {
		max = ff[0].Id + 1
	}

	k := datastore.NewKey(c, "File", "", max, nil);
	f.Id = max
	if _, err := datastore.Put(c, k, f); err != nil {
		c.Errorf("SAVE FILE INFO ERROR: %v", err)
		renderJSON(w, r, &file.File{})
	}
	renderJSON(w, r, f)
}

func DownloadHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	vars := mux.Vars(r)

	id, _ := strconv.ParseInt(vars["id"], 10, 64)
	k := datastore.NewKey(c, "File", "", id, nil);
	f := new(file.File)
	if err := datastore.Get(c, k, f); err != nil {
		c.Errorf("GET FILE INFO: %v",  err)
		render404(w, r, "")
	}
	if strings.Index(f.Mime, "image/") == 0 {
		w.Header().Set("Age","57162")
		w.Header().Set("Cache-Control","max-age=315360000")
		w.Header().Set("Expires","Wed, 14 Sep 2022 15:48:08 GMT")
	} else {
		w.Header().Set("Content-Disposition", `attachment; filename="` + f.Name + `"`)
	}
	blobstore.Send(w, appengine.BlobKey(f.BlobId))
}
